<template>
	<el-dialog v-model="visible" :title="isRole ? '设置职务权限' : !dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :width="isRole ? 900 : 600" :destroy-on-close="true">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px" @keyup.enter="submitHandle()">
			<el-form-item prop="position_name" label="职务名称">
				<el-input v-model="dataForm.position_name" placeholder="名称" :disabled="isRole"></el-input>
			</el-form-item>
			<el-form-item prop="parentName" label="所属部门" class="org-list">
				<el-popover ref="orgListPopover" placement="bottom-start" trigger="click" :width="400" popper-class="popover-pop" :disabled="isRole">
					<template #reference>
						<el-input v-model="dataForm.parentName" :readonly="true" placeholder="上级部门" :disabled="isRole">
							<template #suffix>
								<svg-icon v-if="dataForm.pid !== '0' && !isRole" icon="icon-close-circle" @click.stop="treeSetDefaultHandle()"></svg-icon>
							</template>
						</el-input>
					</template>
					<div class="popover-pop-body">
						<el-tree
							ref="orgListTree"
							:data="orgList"
							:props="{ label: 'department_name', children: 'children' }"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							accordion
							@current-change="treeCurrentChange"
						>
						</el-tree>
					</div>
				</el-popover>
			</el-form-item>
			<el-form-item prop="position_remark" label="备注">
				<el-input v-model="dataForm.position_remark" placeholder="备注" :disabled="isRole"></el-input>
			</el-form-item>
			<el-row v-if="isRole">
				<el-col :span="24">
					<el-form-item label="菜单权限">
						<div class="w100">
                            <el-scrollbar max-height="400px" always :min-size="30">
                                <el-tree ref="menuListTree" :data="menuList" :props="{ label: 'permission_name', children: 'children' }" node-key="id" show-checkbox default-expand-all check-strictly @check="handleChange">
                                </el-tree>
                            </el-scrollbar>
                        </div>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12">
					<el-form-item label="数据权限">
						<el-tree ref="orgListTree" :data="orgList" :props="{ label: 'name', children: 'children' }" node-key="id" accordion show-checkbox>
						</el-tree>
					</el-form-item>
				</el-col> -->
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useRoleApi, useRoleAddApi, useSetRoleApi, useGetRoleApi } from '@/api/role'
import { useMenuListApi, useMenuNavApi } from '@/api/menu'
import { useOrgListApi } from '@/api/org'
import { createRouteList } from '@/router'
import { timeResetDate } from '@/utils/tool'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const isRole = ref(false)
const menuList = ref([])
const orgList = ref([])
const menuListTree = ref()
const orgListTree = ref()
const dataFormRef = ref()
const orgListPopover = ref()
const allRoute = ref([]);
const dataForm = reactive({
	id: '',
	position_name: '',
	menuIdList: [] as any[],
	orgIdList: [],
	department_id: '',
	parentName: '',
	position_remark: ''
})

const init = (id?: number, role?: any) => {
	visible.value = true
	dataForm.id = ''
	dataForm.department_id = ''
	dataForm.position_name = ''
	dataForm.position_remark = ''
	dataForm.parentName = ''
    if (role) {
        isRole.value = true;
        getRoleApi(id);
    } else {
        isRole.value = false;
    }
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
	// if (menuListTree.value) {
	// 	menuListTree.value.setCheckedKeys([])
	// }
	// if (orgListTree.value) {
	// 	orgListTree.value.setCheckedKeys([])
	// }

	// id 存在则为修改
	if (id) {
        dataForm.id = id;
		getRole(id)
	} else {
        nextTick(() => {
            orgListTree.value.setCurrentKey('')
        })
    }

	// // 菜单列表
	// getMenuList()

	// // 部门列表
	// getOrgList()
}

// 获取菜单列表
const getMenuList = async () => {
    const { data } = await useMenuNavApi();
    allRoute.value = createRouteList(data);
	useMenuListApi().then(res => {
		menuList.value = createTreeData(res.data);
	})
}
const createTreeData = (list: any[]|undefined) => {
    const treelist = [];
    list.forEach(item => {
        if (item.children?.length) {
            item.children.forEach(e => {
                e.disabled = !allRoute.value.includes(e.route);
            });
        }
        const additem = {
            ...item,
            disabled: !allRoute.value.includes(item.route),
            children: [],
        }
        // 有子菜单的情况
		if (item.children && item.children.length > 0) {
			additem.children?.push(...createTreeData(item.children))
		}
        treelist.push(additem);
    })
    return treelist;
}
// 获取职务权限
const getRoleApi = (id) => {
	useGetRoleApi({position_id: id}).then(res => {
		if (res.data?.length) {
            res.data.forEach(item => menuListTree.value.setChecked(item, true))
        }
	})
}
const handleChange = (data, nodes) => {
    // 选中子节点，默认选中父节点
    if (data.type == 1 && nodes.checkedKeys.includes(data.id)) {
        const parentNode = menuList.value.find(i => i.id == data.pid);
        if (parentNode) {
            menuListTree.value.setChecked(parentNode.id, true)
        }
    }
    if (data.type == 2 && nodes.checkedKeys.includes(data.id)) {
        const topNode = menuList.value.find(i => i.children.some(e => e.id == data.pid));
        if (topNode) {
            menuListTree.value.setChecked(topNode.id, true)
            const paraneNode = topNode.children.find(i => i.id == data.pid);
            menuListTree.value.setChecked(paraneNode.id, true)
        }
    }
    // 选中父节点，默认选择所有子节点
    if (data.children?.length) {
        if (nodes.checkedKeys.includes(data.id)) {
            data.children.forEach(item => {
                menuListTree.value.setChecked(item.id, true)
                handleChange(item, {checkedKeys: [item.id]});
            })
        } else {
            data.children.forEach(item => {
                menuListTree.value.setChecked(item.id, false)
                handleChange(item, {checkedKeys: []});
            })
        }
    }
}
const treeCurrentChange = (data: any) => {
	dataForm.department_id = data.id
	dataForm.parentName = data.department_name
	orgListPopover.value.hide()
}
// 上级部门树, 设置默认值
const treeSetDefaultHandle = () => {
	dataForm.department_id = ''
	dataForm.parentName = ''
}
// 获取部门列表
const getOrgList = () => {
	useOrgListApi().then((res: any) => {
		orgList.value = res.data;
	})
}
onMounted(() => {
    getOrgList();
    getMenuList();
})
// 获取信息
const getRole = (id: number) => {
	useRoleApi(id).then((res: any) => {
        delete res.data.created_at;
        delete res.data.updated_at;
        delete res.data.deleted_at;
		Object.assign(dataForm, res.data)

		// dataForm.menuIdList.forEach(item => menuListTree.value.setChecked(item, true))
		// orgListTree.value.setCheckedKeys(dataForm.orgIdList)
        nextTick(() => {
            orgListTree.value.setCurrentKey(dataForm.department_id)
        })
	})
}

const dataRules = ref({
	position_name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	parentName: [{ required: true, message: '必填项不能为空', trigger: 'change' }]
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		// dataForm.orgIdList = orgListTree.value.getCheckedKeys()
		if (isRole.value) {
            dataForm.menuIdList = [...menuListTree.value.getHalfCheckedKeys(), ...menuListTree.value.getCheckedKeys()]
            console.log(JSON.parse(JSON.stringify(dataForm.menuIdList)));
            useSetRoleApi({
                position_id: dataForm.id,
                permission_ids: dataForm.menuIdList
            }).then((result) => {
                if (result) {
                    ElMessage.success({
                        message: '操作成功',
                        duration: 500,
                        onClose: () => {
                            visible.value = false
                            emit('refreshDataList')
                        }
                    })
                }
            }).catch((err) => {
                
            });
            return;
        }
        const params:any = {
            department_id: dataForm.department_id,
            position_name: dataForm.position_name,
            position_remark: dataForm.position_remark,
            sort: 0,
            status: 1
        };
        if (dataForm.id) {
            params.id = dataForm.id;
            params.updated_at = timeResetDate();
        }
        useRoleAddApi(params).then((result) => {
            if (result) {
                ElMessage.success({
                    message: '操作成功',
                    duration: 500,
                    onClose: () => {
                        visible.value = false
                        emit('refreshDataList')
                    }
                })
            }
        }).catch((err) => {
            
        });
	})
}

defineExpose({
	init
})
</script>
